package com.ming.service.impl;

import com.ming.dao.CartDao;
import com.ming.dao.OrderDetailetDao;
import com.ming.dao.OrdersDao;
import com.ming.po.Cart;
import com.ming.po.Orders;
import com.ming.po.ResponseBean;
import com.ming.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {

	@Autowired
	private OrdersDao od;			// 订单Dao层
	@Autowired
	private CartDao cd;				// 购物车Dao层
	@Autowired
	private OrderDetailetDao odd;	// 详细订单Dao层

	/**
	 * 创建订单
	 * @param order
	 * @return
	 */
	@Override
	@Transactional
	public ResponseBean<Integer> createOrders(Orders order) {
		// 订单创建日期
		Date cur = new Date();
		// 调用日期格式化工具类
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String str_cur = sdf.format(cur);

		// 封装订单数据
		order.setOrderDate(str_cur);

		od.saveOrders(order);
		// 返回订单编号Id
		int orderId = order.getOrderId();

		// 生成订单明细数据表
		int result = odd.saveOrderDetailet(orderId);
		if(result>0){
			System.out.println("生成订单明细数据成功");
		}
		// 清空购物车
		Cart cart = new Cart();
		cart.setUserId(order.getUserId());
		cart.setBusinessId(order.getBusinessId());
		cd.removeCart(cart);

		return new ResponseBean<>(orderId);
	}

	/**
	 * 根据订单Id获取订单列表
	 * @param orderId
	 * @return
	 */
	@Override
	public ResponseBean<Orders> getOrderById(Integer orderId) {
		return new ResponseBean<>(od.getOrdersById(orderId));
	}

	/**
	 * 根据用户Id查询相关的订单列表
	 * @param userId
	 * @return
	 */
	@Override
	public ResponseBean<List<Orders>> listOrdersByUserId(String userId){
		return new ResponseBean<>(od.listOrdersByUserId(userId));
	}

	/**
	 * 根据用户Id查询相关的订单详情列表
	 * @param userId
	 * @return
	 */
	@Override
	public ResponseBean<List<Orders>> listOrdersDetailByUserId(String userId) {
		List<Orders> list = od.listOrdersByUserId(userId);
		if(!list.isEmpty()){
			for (int i = 0; i < list.size(); i++) {
				Integer orderId = list.get(i).getOrderId();
				Orders order = this.getOrderById(orderId).getData();	// 调用能查复杂属性信息的订单查询方法
				list.set(i,order);
			}
		}
		return new ResponseBean<>(list);
	}
}
